﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor.Operations
{
	internal class NewMapElement : Operation
	{
        Vector2 Position;
		System.Type ElementType;
        Engine.Selection ItemAdded;

		public NewMapElement(System.Type Type, Vector2 Position)
		{
			ElementType = Type;
            this.Position = Position;
		}

		internal override ReturnCode Do(EditorState ES)
		{
            Data.MapElement _element = Activator.CreateInstance(ElementType) as Data.MapElement;
            _element.SetPosition(Position);
            ES.Map.Elements.Add(_element);

            ItemAdded = new Engine.Selection(_element.SelectionType(), ES.Map.Elements.Count - 1, 0, 0);
            ES.AddNewMapElementToTree(_element, ItemAdded.TopIndex);
            ES.SelectItem(ItemAdded);

            var Attributes = ElementType.GetCustomAttributes(true);
            foreach (var Attr in Attributes)
                if (Attr is Engine.EditorInitializationAttribute)
                    ( Attr as Engine.EditorInitializationAttribute ).Initialize_NewItem(_element, new EditorStateInterface(ES));

			return ReturnCode.AddToUndoStack;
		}

		internal override void Undo(EditorState ES)
		{
			ES.Map.Elements.RemoveAt(ItemAdded.TopIndex);
            ES.RemoveMapElementFromTree(ItemAdded.TopIndex);
            ES.SelectItem(Engine.Selection.None);
		}
	}
}
